<template>
  <div class="mod-config">
    <div v-if="member">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()" ref="dataForm">
        <el-form-item>
          <el-input v-model="dataForm.adName" placeholder="渠道名称"></el-input>
        </el-form-item>
        <el-form-item label="渠道分类：">
          <el-select v-model="dataForm.channelId" placeholder="请选择">
            <el-option
              v-for="item in useroption1"
              :key="item.id"
              :label="item.channelName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search()">查询</el-button>
          <el-button type="primary" @click="addChannel()">添加渠道</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        style="width: 100%;"
      >
        <el-table-column prop="adName" header-align="center" align="center" label="渠道名称"></el-table-column>
        <el-table-column prop="adHash" header-align="center" align="center" label="投放标识"></el-table-column>
        <el-table-column prop="channelName" header-align="center" align="center" label="渠道分类"></el-table-column>
        <el-table-column prop="surveyName" header-align="center" align="center" label="投放表单"></el-table-column>
        <el-table-column prop="gmtCreated" header-align="center" align="center" label="创建时间"></el-table-column>
        <el-table-column prop="remark" header-align="center" align="center" label="备注"></el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" label="数据统计" width="150px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="statisticShow(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right" header-align="center" align="center" label="操作" width="250px">
          <template slot-scope="scope">
            <el-button type="text" size="small"
                       v-clipboard:copy="scope.row.redirectUrl"
                       v-clipboard:success="onCopy"
                       v-clipboard:error="onError"
            >复制URL</el-button>
            <el-button type="text" size="small" @click="showQrCode(scope.row.adName, scope.row.adHash)">生成二维码</el-button>
            <el-button type="text" size="small" @click="delThrow(scope.row.id)">删除</el-button>
            <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>

      <!--添加投放s-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="visible1"
        title="添加渠道"
      >
        <el-form
          :model="dataForm1"
          ref="dataForm1"
          label-width="150px"
          :rules="rules"
        >
          <el-form-item label="渠道名称:" prop="adName">
            <el-input v-model="dataForm1.adName"></el-input>
          </el-form-item>
          <el-form-item label="选择表单:" prop="adFormType">
            <el-select v-model="dataForm1.adFormId" placeholder="请选择">
              <el-option
                v-for="item in useroption"
                :key="item.id"
                :label="item.surveyName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择渠道分类:" prop="channelIdList">
            <el-select v-model="dataForm1.channelIdList" multiple placeholder="请选择">
              <el-option
                v-for="item in appLabel"
                :key="item.id"
                :label="item.channelName"
                :value="item.id">
              </el-option>
            </el-select>
            <div>可多选</div>
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input v-model="dataForm1.remark" placeholder="选填"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible1 = false">取消</el-button>
          <el-button type="primary" @click="channelForm">确定</el-button>
        </span>
      </el-dialog>
      <!--添加渠道e-->

      <!--修改投放s-->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="visible2"
        title="添加投放"
      >
        <el-form
          :model="dataForm2"
          ref="dataForm2"
          label-width="150px"
          :rules="rules1"
        >
          <el-form-item label="投放描述:" prop="adName">
            <el-input v-model="dataForm2.adName"></el-input>
          </el-form-item>
          <el-form-item label="选择表单:">
            {{ dataForm2.surveyName }}
          </el-form-item>
          <el-form-item label="选择渠道:">
            {{ dataForm2.channelName }}
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input v-model="dataForm2.remark" placeholder="选填"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible2 = false">取消</el-button>
          <el-button type="primary" @click="editChannelForm">确定</el-button>
        </span>
      </el-dialog>
      <!--修改渠道e-->
    </div>

    <!--数据统计-->
    <statistic-list v-else ref="statisticList" @goBack="goBack"></statistic-list>
  </div>
</template>

<script>
  import QRCode from "qrcode";
  import StatisticList from './throwStatisticList'
  export default {
    data() {
      return {
        member: true,
        isEdit: false,
        visibleIntegralList: false,
        dataForm: {
          channelType: null,
          channelName: ''
        },
        dataForm1: {
          adName: '',
          adFormId: '',
          adFormType: 1,
          channelIdList: [],
          remark: ''
        },
        useroption1: [],
        rules: {
          adName: [
            { required: true, message: '请输入投放描述', trigger: 'blur' }
          ],
          adFormType: [
            { required: true, message: '请选择表单', trigger: 'blur' }
          ],
          channelIdList: [
            { required: true, message: '请选择渠道', trigger: 'blur' }
          ]
        },
        rules1: {
          adName: [
            { required: true, message: '请输入投放描述', trigger: 'blur' }
          ]
        },
        zanConfig: 0,
        visible1: false,
        dataList: [],
        dataListLoading: false,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        appLabel: [],
        useroption: [],
        codeImg: '',
        visible2: false,
        dataForm2: {}
      }
    },
    components: {
      StatisticList
    },
    activated() {
      this.getAppLabel()
      this.getDataList()
      this.getForm()
    },
    methods: {
      search() {
        this.pageIndex = 1
        this.getDataList()
      },
      showQrCode(adName, url) {
        var opts = {
          errorCorrectionLevel: "H",
          type: "image/jpeg",
          rendererOpts: {
            quality: 0.3
          }
        };
        let redirectUrl = 'http://yiban-api-test.qingclass.com/yiban-app/mpApi/landing/wx3596133503dd469e?redirectType=2&adHash='+url
        if(process.env.NODE_MYSELF) {
          redirectUrl = 'https://yiban-c-api.ivykid.com/yiban-app/mpApi/landing/wxa1874f7d1d90e3ed?redirectType=2&adHash='+url
        }
        QRCode.toDataURL(redirectUrl, opts, (err, url) => {
          this.codeImg = url;
        });
        this.$alert(`<img style="width: 200px;" src="${this.codeImg}" />`, '生成二维码', {
          dangerouslyUseHTMLString: true,
          center: true,
          confirmButtonText: '保存二维码',
          callback: action => {
            if(action === 'confirm') {
              let a = document.createElement('a');
              let filename = `${adName}的二维码.png`;
              a.href = this.codeImg;
              a.download = filename;
              a.click();
            }
            // this.$message({
            //   type: 'info',
            //   message: `action: ${ action }`
            // });
          }
        });
      },
      onCopy() {
        this.$message({
          message: '复制成功',
          type: 'success'
        })
      },
      onError() {
        this.$message.error('复制失败');
      },
      edit(obj) {
        this.visible2 = true
        this.dataForm2.id = obj.id
        this.dataForm2.adName = obj.adName
        this.dataForm2.surveyName = obj.surveyName
        this.dataForm2.channelName = obj.channelName
        this.dataForm2.remark = obj.remark
      },
      getAppLabel() {
        this.$http({
          url: this.$http.adornUrl('/market/marketchannel/channelNameList'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.appLabel = data.channelInfo
            this.useroption1 = [{id:null, channelName: '全部'}, ...data.channelInfo]
          }
        })
      },
      getForm() {
        this.$http({
          url: this.$http.adornUrl('/market/marketsurvey/getAllForm'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.useroption = data.list
          }
        })
      },
      statisticShow(id) {
        this.member = false
        this.$nextTick(() => {
          this.$refs.statisticList.init(id)
        })
      },
      goBack() {
        this.member = true
      },
      editChannelForm() {
        this.$refs['dataForm2'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl('/market/marketad/updateAd'),
              method: 'post',
              data: this.$http.adornData(this.dataForm2)
            }).then(({data}) => {
              if(data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible2 = false
                    this.getDataList()
                  }
                });
              } else {
                this.$message({
                  message: data.msg,
                  type: 'error',
                  duration: 1500,
                });
              }
            })
          }
        })
      },
      // 获取数据列表
      getDataList() {
        let basetUrl = 'http://yiban-api-test.qingclass.com/yiban-app/mpApi/landing/wx3596133503dd469e?redirectType=2&adHash='
        if(process.env.NODE_MYSELF) {
          basetUrl = 'https://yiban-c-api.ivykid.com/yiban-app/mpApi/landing/wxa1874f7d1d90e3ed?redirectType=2&adHash='
        }
        this.dataListLoading = true
        this.dataForm.page = this.pageIndex
        this.dataForm.limit = this.pageSize
        this.$http({
          url: this.$http.adornUrl('/market/marketad/list'),
          method: 'get',
          params: this.$http.adornParams(this.dataForm)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$refs['dataForm'].resetFields()
            this.dataList = data.page.list
            const that = this
            data.page.list.map((item, index)=> {
              that.dataList[index].redirectUrl = basetUrl+item.adHash
            })
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      addChannel() {
        this.dataForm1 = {
          adName: '',
          adFormType: 1,
          adFormId: '',
          channelIdList: [],
          remark: ''
        }
        this.visible1 = true
      },
      delThrow(id) {
        this.$confirm('是否确定删除该条投放?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/market/marketad/delete'),
            method: 'post',
            data: [id]
          }).then(({data}) => {
            if(data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              });
            }
          })
        }).catch(() => {

        })
      },
      channelForm() {
        this.$refs['dataForm1'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl('/market/marketad/save'),
              method: 'post',
              data: this.$http.adornData(this.dataForm1)
            }).then(({data}) => {
              if(data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible1 = false
                    this.getDataList()
                  }
                });
              } else {
                this.$message({
                  message: data.msg,
                  type: 'error',
                  duration: 1500,
                });
              }
            })
          }
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      }
    }
  }
</script>
<style>
  .margin_10{
    margin-bottom: 10px;
  }
  .text_r{
    text-align: right;
    padding-right: 15px;
  }
  .inineBlock{
    display: inline-block;
  }
  img{
    width: 100%;
    height: auto;
  }
</style>
